package com.tanhua.server.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.pojo.SoundTime;
import com.tanhua.server.vo.SoundVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class SoundService {

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private IMService imService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    /**
     * 发送语音
     *
     * @param soundFile 语文文件
     * @return
     */
    public Boolean sendSound(MultipartFile soundFile) {
        User user = UserThreadLocal.get();
        Sound sound = new Sound();

        //设置基础信息
        sound.setUserId(user.getId());

        try {
            //上传语音
            StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), StrUtil.subAfter(soundFile.getOriginalFilename(), '.', true), null);
            //设置语音url
            sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            String soundId = soundApi.saveSound(sound);
            return StrUtil.isNotEmpty(soundId);
        } catch (Exception e) {
            log.error("发布语音失败！file = " + soundFile.getOriginalFilename(), e);
        }
        return null;
    }

    /*public SoundVo getSound() {
        Long userId = UserThreadLocal.get().getId();
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(userId);
        SoundVo soundVo = new SoundVo();
        soundVo.setUserId(userId);
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setNickname(userInfo.getNickName());
        soundVo.setGender(userInfo.getSex().name().toLowerCase());
        soundVo.setAge(userInfo.getAge());
        List<Sound> soundList = soundApi.querySounds();
        Collections.shuffle(soundList);
        soundVo.setSoundUrl(soundList.get(0).getSoundUrl());
        soundVo.setRemainingTimes(7);
        return soundVo;
    }*/

    /**
     * 接收语音
     *
     * @return
     */
    public SoundVo getSound() {
        // 获取登录用户信息
        Long userId = UserThreadLocal.get().getId();
        SoundVo soundVo = new SoundVo();

        // 从语音库获取语音
        List<Sound> soundList = soundApi.querySounds();

        // 重新洗牌, 获取当前发布语音的用户信息
        Collections.shuffle(soundList);
        Long id = null;

        // 判断, 不能获取自己的语音
        for (Sound sound : soundList) {
            if (!ObjectUtil.equals(sound.getUserId(),userId)){
                id = sound.getUserId();
                break;
            }
        }

            // 获取当前用户的读取次数
            SoundTime soundTime = soundApi.querySoundByUserId(userId);
            Integer number = soundTime.getNumber();
            int max = Math.max(0, number);

            UserInfo userInfo = userInfoService.queryUserInfoByUserId(id);

            // 封装信息
            soundVo.setUserId(id);
            soundVo.setAvatar(userInfo.getLogo());
            soundVo.setNickname(userInfo.getNickName());
            soundVo.setGender(userInfo.getSex().name().toLowerCase());
            soundVo.setAge(userInfo.getAge());
            soundVo.setSoundUrl(soundList.get(0).getSoundUrl());
            soundVo.setRemainingTimes(max);

            return soundVo;
    }

    /**
     * 加为好友后删除双方的语音
     *
     * @param likeUserId  好友id
     * @return
     */
    public Boolean likeUser(Long likeUserId) {
        // 获取当前登录用户信息
        User user = UserThreadLocal.get();
        // 调用之前的喜欢方法
        Boolean result = userLikeApi.likeUser(user.getId(), likeUserId);
        if (!result){
            return false;
        }
        // 双方都加为好友后, 调用删除方法
        if (userLikeApi.isMutualLike(user.getId(), likeUserId)){
            imService.contactUser(likeUserId);
            soundApi.deleteSound(user.getId(),likeUserId);
        }

        return true;
    }

    public Boolean notLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return userLikeApi.notLikeUser(user.getId(), likeUserId);
    }
}
